package com.copyctrl.campus.portal.controller;

import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.constant.RedisConstant;
import com.copyctrl.campus.common.domain.Message;
import com.copyctrl.campus.common.model.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.Set;

/**
 * @author:JH
 * @version:1.0
 */
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    StringRedisTemplate redisTemplate;
    // 先设计redis中的key值，是否持久化到mysql 如果持久化就设计新表。
    // 不作持久化，仅存入redis中，设置过期时间
    // 暂时不再做分页查询，过期时间倒是有个稍微好的处理方法，每次查询历史记录时把当前时间传进来，
    // 查询当前时间戳减7天的时间戳到当前时间戳的数据返回前端，异步查询0到当前时间戳减30天的时间戳删除数据

    //删除（未读）聊天记录
    @DeleteMapping("/{userid}/{from}")
    public ApiResponse deleteNotRead(@PathVariable String userid, @PathVariable String from){
        Set<String> strings = redisTemplate.opsForZSet().range(RedisConstant.MESSAGE_USER_NOT_READ + userid, 0, -1);
        for (String string : strings) {
            Message message = JSONUtil.toBean(string, Message.class);
            if (Objects.equals(message.getFromId(), from)){
                Long remove = redisTemplate.opsForZSet().remove(RedisConstant.MESSAGE_USER_NOT_READ + userid, string);
            }
        }
        return ApiResponse.ofSuccess("ok");
    }

    //TODO 获取历史聊天记录(前端点击查看更多消息)
    @GetMapping("/{userid}/{from}")
    public ApiResponse getAll(@PathVariable String userid, @PathVariable String from){
        Integer i1 = new Integer(userid);
        Integer i2 = new Integer(from);
        String key = "";
        if (i1 > i2) {
            key = from + userid;
        } else {
            key = userid + from;
        }
        long min = System.currentTimeMillis() - RedisConstant.DAYS;
        System.out.println("min="+min+",now="+System.currentTimeMillis());

        Set<String> history = redisTemplate.opsForZSet().rangeByScore(RedisConstant.MESSAGE_ALL + key, min, System.currentTimeMillis());
        Long aLong = redisTemplate.opsForZSet().removeRangeByScore(RedisConstant.MESSAGE_ALL + key, 0, min);
        System.out.println(aLong);
        return ApiResponse.ofSuccess(history);
    }
}
